package tsvetanv.inventory.util.validation;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import tsvetanv.inventory.model.Article;
import tsvetanv.inventory.model.Product;
import tsvetanv.inventory.service.ProductService;

/**
 * The ProductValidator class realize business-logic validation of user input
 * for {@link Product} form.
 * 
 * @author Tsvetan Vasilev
 * 
 */

public class ProductValidator implements Validator {
	private static Logger logger = Logger.getLogger(ProductValidator.class);

	@Autowired
	private ProductService service;

	// --- Constructors, Getters, Setters --------------------------------------

	public void setService(ProductService service) {
		this.service = service;
	}

	// --- Methods -------------------------------------------------------------

	public boolean supports(Class clazz) {
		return Product.class.isAssignableFrom(clazz);
	}

	/**
	 * Specify custom business-logic validation on {@link Product}'s fields.
	 */
	public void validate(Object target, Errors errors) {
		logger.info("START validate() method");
		Product product = (Product) target;

		// validation on required "Name", "Description" fields is done in
		// initBind() method of ArticleEditFormController

		// product's name should be unique
		if (service.isThereAnotherProductInDBWithSameName(product)) {
			errors.rejectValue("name", "product.name.unique");
		}
	}
}
